<template>
  <div class="recipe-container">
    <van-grid
      column-num="2"
      :border="false"
      :gutter="16"
      v-if="recipe.length > 0"
    >
      <van-grid-item
        v-for="item in recipe"
        :key="item.id"
        @click="handleRecipeClick(item)"
      >
        <template #icon>
          <van-image
            fit="cover"
            src="https://tse3-mm.cn.bing.net/th/id/OIP-C.GSmJh-jKBK6A6FQSHtPu-gHaE4?w=266&h=186&c=7&r=0&o=5&dpr=1.3&pid=1.7"
            alt="菜谱图片"
            class="recipe-image"
          />
        </template>
        <template #text>
          <div class="recipe-info">
            <h3 class="recipe-name">{{ item.title }}</h3>
            <div class="author-info">
              <van-image
                class="author-avatar"
                src="https://tse1-mm.cn.bing.net/th/id/OIP-C.XA9KOfDBo2EpCI-kCkBIBgAAAA?w=149&h=166&c=7&r=0&o=5&dpr=1.3&pid=1.7"
                round
                width="24"
                height="24"
                alt="作者头像"
              />
              <span class="author-name">{{ item.user.username }}</span>
            </div>
          </div>
        </template>
      </van-grid-item>
    </van-grid>
  </div>
</template>

<script setup>
import api from "@/api";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";

//接收菜谱
const recipe = ref([]);
const admin = JSON.parse(localStorage.getItem("admin"));
const router = useRouter();

const recommendRecipe = () => {
  if (admin == null) {
    api.postReq("/recipe/getRecipes").then((res) => {
      let result = res.data;
      recipe.value = result.data;
    });
  } else {
    api.postReq("/recipe/getRecipeListByUserId?id=" + admin.id).then((res) => {
      let result = res.data;
      recipe.value = result.data;
    });
  }
};

// 处理菜谱点击事件
const handleRecipeClick = (item) => {
    console.log(item)
  // 1. 发送浏览记录统计请求
  const browseRecode = {
    browseId: item.id,
    userId: admin ? admin.id : null, // 如果有登录用户则传递用户ID
    browseType: false,
  };
  console.log(browseRecode)
  // 先发送浏览记录请求，再跳转
  api
    .postReq("/recipe/addViewRecord", browseRecode)
    .then(() => {
      // 2. 跳转至详情页，并携带菜谱ID
      router.push({
        path: "/recipe-detail",
        query: { id: item.id }, // 将菜谱ID作为参数传递
      });
    })
    .catch((error) => {
      console.error("记录浏览失败:", error);
      // 即使记录失败也继续跳转
      router.push({
        path: "/recipe-detail",
        query: { id: item.id },
      });
    });
};

onMounted(() => {
  recommendRecipe();
});

</script>

<style scoped>
.recipe-container {
  padding: 10px;
}
.recipe-image {
  width: 100%;
  height: 180px;
  border-radius: 20px;
}
.recipe-info {
  padding: 8px 0;
}
.recipe-name {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.author-info {
  display: flex;
  align-items: center;
}
.author-avatar {
  margin-right: 4px;
}
.author-name {
  font-size: 12px;
  color: #666;
}
</style>
